package org.example.exampreparationtreasure.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import org.example.exampreparationtreasure.config.JwtConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    @Autowired
    private JwtConfig jwtConfig;

    /**
     * 生成jwt令牌
     * @param username 用户名 userId 用户id
     * @return Jwt令牌
     */
    public String generateToken(String username,Long userId) {
        Date expireDate = new Date(System.currentTimeMillis() + jwtConfig.getExpire() * 1000 * 24);

        Map<String,Object> claims = new HashMap<>();
        claims.put("username",username);
        claims.put("userId",userId);

        SecretKey key = Keys.hmacShaKeyFor(jwtConfig.getSecret().getBytes());
        return Jwts.builder()
                .claims(claims)
                .issuedAt(new Date())
                .subject("MAMBO")
                .expiration(expireDate)
                .signWith(key)
                .compact();
    }

    /**
     * @param token jwt令牌
     * @return claims
     */
    public Claims parseToken(String token) {
        try {
            SecretKey key = Keys.hmacShaKeyFor(jwtConfig.getSecret().getBytes());
            return Jwts.parser()
                    .verifyWith(key)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (Exception e) {
            System.err.println("JWT解析失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("JWT token解析失败", e);
        }
    }

    /**
     * @param token jwt令牌
     * @return 用户名
     */
    public String getUsernameByToken(String token) {
        return (String) parseToken(token).get("username");
    }

    /**
     * @param token jwt令牌
     * @return 用户id
     */
    public Long getUserIdByToken(String token) {
        try {
            Object userIdObj = parseToken(token).get("userId");
            System.out.println("JWT中的userId类型: " + (userIdObj != null ? userIdObj.getClass().getName() : "null"));
            System.out.println("JWT中的userId值: " + userIdObj);
            
            if (userIdObj == null) {
                throw new RuntimeException("JWT token中没有userId字段");
            }
            
            // 处理不同的数字类型
            if (userIdObj instanceof Long) {
                return (Long) userIdObj;
            } else if (userIdObj instanceof Integer) {
                return ((Integer) userIdObj).longValue();
            } else if (userIdObj instanceof String) {
                return Long.parseLong((String) userIdObj);
            } else {
                throw new RuntimeException("JWT token中userId字段类型不支持: " + userIdObj.getClass().getName());
            }
        } catch (Exception e) {
            System.err.println("获取userId失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("从JWT token获取userId失败", e);
        }
    }

    /**
     * @param token jwt令牌
     * @return 是否过期
     */
    public boolean isTokenExpired(String token) {
        return parseToken(token).getExpiration().before(new Date());
    }
}
